import React from "react";
import routeWithUserSession from "@/components/ApplicationArea/routeWithUserSession";
import PageHeader from "@/components/PageHeader";
import {  ControllerType } from "@/components/items-list/ItemsList";
import { BrowserRouter as Router,Link } from 'react-router-dom';//
import "./Contract.css";
import {Button, Col, Divider,Menu, Form, Input, Row, Table, ConfigProvider, Layout, Tree,Modal,Select} from "antd/lib";
import Dropdown from "antd/lib/dropdown";
import zhCN from 'antd/es/locale/zh_CN';
import ContractSeal from "@/services/contractseal";
// import { createHashHistory } from 'history';
// const hashHistory = createHashHistory();
import {createBrowserHistory} from 'history'
import Enums from "@/services/enums";
import {currentUser} from "@/services/auth";
import routes from "@/services/routes";
import {WarningOutlined,SecurityScanTwoTone,DownOutlined,AppstoreFilled, UpOutlined} from "@ant-design/icons";
import QueryShowField from "@/services/queryshowfield";
import CreateQueryShowFieldDialog from "@/components/enums/QueryShowFieldDialog";
import notification from "@/services/notification";
import Contracts from "@/services/contracts";
import Customer from "@/services/customer";
import {get} from "lodash";
const { confirm } = Modal;
const customHistory = createBrowserHistory();
const { Sider } = Layout;
const getRowClassName = (record, index) => {
  let className = '';
  if (index % 2 === 0) className = "oddRow";
  return className
}
class SealList extends React.Component {
  state = {
    page: 1,
    pagesize: 15,
    total:15,
    loading: false,
    code: '',
    name: '',
    contractcode: localStorage.getItem("contractseallistcode") || '',
    contractname: localStorage.getItem("contractseallistname") || '',
    data: [],
    gData: [],
    selectedKeys: '',
    selectedTitle: '',
    party_a: localStorage.getItem("contractseallistparty_a") || '',
    seltype:  "1",
    departmentid: localStorage.getItem("contractseallistdepartmentid") || [],//--经办部门
    departmentdata:[],//HRP部门表
    queryshowfielddata: [],
    showall: false,
  };
  static propTypes = {
    controller: ControllerType.isRequired,
  };
    items=[{
      name:"cght",
      slug:"imgs",
      tags:"tags",
      is_draft:"df",
      is_archived:true
    }];
  componentWillMount() {
    this.fieldsshowload("1");
    this.loadData();
    let param={
      page: this.state.page,
      pagesize: this.state.pagesize,
      code: this.state.code,
      name: this.state.name,
      contractcode: this.state.contractcode,
      contractname: this.state.contractname,
      departmentid: this.state.departmentid,
      type: this.state.selectedKeys,
      userid: currentUser.id,
      party_a: this.state.party_a,
      seltype:this.state.seltype,
      datadown: false,
    }
    this.fetch(param);
  }
  fetch = (params = {}) => {
    this.setState({ 
      loading: true,
      seltype: params.seltype,
     });
     if(params.datadown){
      let AjaxUrl = 'api/contractseal/list';
      fetch(AjaxUrl ,{
       method: 'POST',
       body: window.JSON.stringify(params),
       credentials: 'include',
       headers: new Headers({
         'Content-Type': 'application/json'
       })}).then((response) => {
       response.blob().then(blob => {
         const aLink = document.createElement('a');
         document.body.appendChild(aLink);
         aLink.style.display='none';
         const objectUrl = window.URL.createObjectURL(blob);
         aLink.href = objectUrl;
         aLink.download = '合同用印列表.xlsx';
         aLink.click();
         document.body.removeChild(aLink);
       });
     }).catch((error) => {
       console.log(error);
     });
    }
    else{
      ContractSeal.getlist(params).then(data => {
        this.setState({
            loading: false,
            data:data.data,
            page: params.page,
            pagesize: params.pagesize,
            total: data.total,
        });
    });
    }

  };
  handlesel = (index) => {
    let datadown =false;
    if(index===2){
      datadown =true;
    }
    let param={
      page: 1,
      pagesize: this.state.pagesize,
      code: this.state.code,
      name: this.state.name,
      contractcode: this.state.contractcode,
      contractname: this.state.contractname,
      departmentid: this.state.departmentid,
      type: this.state.selectedKeys,
      userid: currentUser.id,
      party_a: this.state.party_a,
      seltype:this.state.seltype,
      datadown: datadown,
    }
    this.fetch(param);
  };
  tabsClick = e => {
    this.fieldsshowload(e.key);
    let param={
      page: 1,
      pagesize: this.state.pagesize,
      code: this.state.code,
      name: this.state.name,
      contractcode: this.state.contractcode,
      contractname: this.state.contractname,
      departmentid: this.state.departmentid,
      type: this.state.selectedKeys,
      userid: currentUser.id,
      party_a: this.state.party_a,
      seltype: e.key,
      datadown: false,
    }
    this.fetch(param);
  };
   handleTableChange = (pagination, filters, sorter) => {
    let field=sorter.field;
    let order=0;
    if(sorter.order==="descend"){
      order=1;
    }
    let param={
      field: field,
      order: order,
      page: pagination.current,
      pagesize: pagination.pageSize,
      code: this.state.code,
      name: this.state.name,
      contractcode: this.state.contractcode,
      contractname: this.state.contractname,
      departmentid: this.state.departmentid,
      type: this.state.selectedKeys,
      userid: currentUser.id,
      party_a: this.state.party_a,
      seltype:this.state.seltype,
      datadown: false,
    }
    this.fetch(param);
  };
  handleDelete = record => {
    if(record.status !==0)
    {
       notification.error("只有在草稿状态可以删除，删除失败！");
       return;
    }
    confirm({
      title: '确定删除合同用印?',
      icon: <WarningOutlined />,
      content: record.name,
      okText: '确定',
      okType: 'danger',
      cancelText: '取消',
      onOk: () => {
        ContractSeal.delete(record).then(()=>{
          notification.success("合同用印删除成功.");
          let param={
            page: 1,
            pagesize: this.state.pagesize,
            code: this.state.code,
            name: this.state.name,
            contractcode: this.state.contractcode,
            contractname: this.state.contractname,
            departmentid: this.state.departmentid,
            type: this.state.selectedKeys,
            userid: currentUser.id,
            party_a: this.state.party_a,
            seltype:this.state.seltype,
            datadown: false,
          }
          this.fetch(param);
        }).catch(error => {
          notification.error(get(error, "response.data.message", "删除失败."));
        });
      },
    });
  };
  loadData=()=> {
    Enums.items("contract_enum").then(data => {
      const loop = (das, index) => {
        let items=[];
        das.forEach((item) => {
          item.icon= <SecurityScanTwoTone />;
          if (item.children) {
            item.children= loop(item.children, index+1);
          }
          items.push(item);
        });
        return items;
      };
      let datas=loop(data,0);
      this.setState({
        loading: false,
        gData: datas,
        selectedKeys: '',
        selectedTitle: '',
      });
    });
    let params={
      billtype: "",
      id: 0,
    }
    Contracts.getsellist(params).then(data => {
      this.setState({
        contractsdata: data,
      });
    });
    params={
      code: "",
      name: "",
      userid: currentUser.id,
    }
    Customer.querydepartment(params).then(data => {
      this.setState({
        departmentdata: data,
      });
    });
  }
  handleclear = () => {
    this.setState({
      code: '',
      name: '',
      contractcode: '',
      contractname: '',
      data: [],
      gData: [],
      selectedKeys: '',
      selectedTitle: '',
      party_a:  '',
      departmentid:  [],//--经办部门
    });

    localStorage.setItem("contractseallistcode", "");
    localStorage.setItem("contractseallistname", "");
    localStorage.setItem("contractseallistparty_a", "");
    localStorage.setItem("contractseallistdepartmentid", "");
  }
  handlefieldshow = () => {
    CreateQueryShowFieldDialog.showModal({ queryshowfield: this.state.queryshowfielddata })
      .onClose((result = {}) => {
        if (result.success) {
          this.fieldsshowload(this.state.seltype);
        }
      }).onDismiss(() => {
      });
  }
  fieldsshowload = (seltype) => {
      QueryShowField.getbycode("contractseallist"+seltype).then(data => {
        this.setState({
          queryshowfielddata: data,
        });
      });
  }
  render() {
    // const { currentPage } = this.state;
      const paginationProps = {
            showSizeChanger: true,
            // showQuickJumper: true,
            total: this.state.total, // 数据总数
            pageSize: parseInt(this.state.pagesize), // 每页条数
            current: parseInt(this.state.page), // 当前页码
            pageSizeOptions: ["10", "20", "30","100"],
            showTotal: ((total) => {
              return `共 ${total} 条`;
            }),
          };
          let listcolumns = [];
          listcolumns.push({
            title: '操作',
           // width: 100,
            key: 'action',
            render: (record) => (
              <span>
              <Button type="primary" >
                { (this.state.seltype==="1" ||this.state.seltype==="2") &&(<a href={`/contract/seal/new/${record.id}`}>查看</a>)}
                { (this.state.seltype==="3" ||this.state.seltype==="4") &&(<a href={`/contract/seal/guidang/${record.id}`}>查看</a>)}
              </Button>
              {record.status ===0 &&
                (<Divider type="vertical" />)}
                {record.status ===0 &&
                (<Button type="primary" onClick={() => this.handleDelete(record)} >
                删除
              </Button>)}
              </span>
            ),
            });
          if (this.state.queryshowfielddata.fieldsshow !== undefined) {
            (this.state.queryshowfielddata.fieldsshow || []).map(item => {
              let items = this.state.queryshowfielddata.fieldsall.filter((p) => {
                return p.key === item;
              });
              if (items.length > 0) {
                listcolumns.push({
                  title: items[0].title,
                  dataIndex: item,
                  key: item,
                  sorter: (a, b) => a[item] > b[item] ? 1 : -1
                })
              }
              return item;
            }
            );
          }
    return (
  <ConfigProvider locale={zhCN}>
      {/*<div className="page-dashboard-list">*/}
          <div  style={{width:"400px",height:"60px"}}>
            <div style={{width:"20px",height:"50px", float: "left"}}>
            </div>
              <div style={{width:"50px",height:"50px", float: "left"}}>
              <img src="/static/images/contractseal.png"/>
            </div>
              <div style={{width:"320px",height:"30px",float:"left"}}>
              <h3 style={{margin:"7px",padding:"0"}}>合同用印列表</h3>
            </div>
          </div>
      <Layout>
        <Layout style={{ padding: '0 24px 24px' }}>
        {this.state.showall && (<><Row style={{ marginBottom: 5 }}>
              <Col span={2}><div style={{ marginTop: "5px", textAlign: "right", marginRight: "10px" }}>
              合同单位:</div></Col>
              <Col span={6}>
              <Input
                value={this.state.party_a}
                onChange={e => {
                  localStorage.setItem("contractseallistparty_a", e.target.value);
                  this.setState({party_a:e.target.value});}}
                placeholder="合同单位"
              />
              </Col>
              <Col span={2}><div style={{ marginTop: "5px", textAlign: "right", marginRight: "10px" }}>
              用印经办部门:</div></Col>
              <Col span={6}>
              <Select style={{ width:  "100%" }}
                    showSearch
                    mode="multiple"
                    allowClear
                    optionFilterProp="children"
                      value={this.state.departmentid}
                      onChange={value => {
                        localStorage.setItem("contractseallistdepartmentid", value);
                        this.setState({departmentid:value});}} >
              {(this.state.departmentdata || []).map(item => (
                <Select.Option key={item.id} value={item.id}>{item.name}</Select.Option>
              ))}
              </Select> 
              </Col>
              </Row></>)}
            <Row style={{ marginBottom: 5 }}>
             <Col span={2}><div style={{ marginTop: "5px", textAlign: "right", marginRight: "10px" }}>
              合同编码:</div></Col>
              <Col span={6}>
              <Input
                value={this.state.contractcode}
                onChange={e => {
                  localStorage.setItem("contractseallistcode", e.target.value);
                  this.setState({contractcode: e.target.value});
                }}
                placeholder="合同编码"
              />
              </Col>
              <Col span={2}><div style={{ marginTop: "5px", textAlign: "right", marginRight: "10px" }}>
              合同名称:</div></Col>
              <Col span={6}>
              <Input
                value={this.state.contractname}
                onChange={e => {
                  localStorage.setItem("contractseallistname", e.target.value);
                  this.setState({contractname:e.target.value});}}
                placeholder="合同名称"
              />
              </Col>
              <Col span={8}>
                <Divider type="vertical" />
                <Button type="primary" onClick={() => this.handlesel(1)} >
                  <i className="fa fa-search m-r-5" />
                  查询
                </Button>
                <Divider type="vertical" />
                <Button onClick={() => this.handleclear()} >
                  清空
                </Button>
                <Divider type="vertical" />
                <Button onClick={() => { this.setState({ showall: !this.state.showall }); }} >
                  {this.state.showall && (<UpOutlined />)}
                  {!this.state.showall && (<DownOutlined />)}
                  {this.state.showall ? '默认' : '更多'}
                </Button>
              </Col>
            </Row>
            <Row style={{ marginBottom: 5 }}>
              <Col span={10}>
                <Button type="primary" >
                  <i className="fa fa-plus m-r-5" />
                  <a href="contract/seal/new/0" style={{ color: "white" }}>新建合同用印</a>
                </Button>
                <Divider type="vertical" />
                <Dropdown
                  trigger={["click"]}
                  overlay={
                    <Menu>
                        <Menu.Item key="change-item-out">
                          <a onMouseUp={() => this.handlesel(2)}>EXCEL导出</a>
                        </Menu.Item>
                      {currentUser.hasPermission("admin") && (<Menu.Divider />)}
                      {currentUser.hasPermission("admin") && (
                        <Menu.Item key="delete-item">
                          <a onMouseUp={() => this.handlefieldshow()}>显示隐藏列</a>
                        </Menu.Item>
                      )}
                    </Menu>
                  }>
                  <Button type="primary" style={{ margin: "10px" }} data-test="CreateButton" >
                    <AppstoreFilled />更多功能
                  </Button>
                </Dropdown>
              </Col>
            </Row>
      <Menu onClick={this.tabsClick} selectedKeys={this.state.seltype} mode="horizontal">
        <Menu.Item key = "1">未用印</Menu.Item>
        <Menu.Item key = "2">已用印</Menu.Item>
        <Menu.Item key = "3">未归档</Menu.Item>
        <Menu.Item key = "4">已归档</Menu.Item>
      </Menu>
                 <div>
                      <Table rowKey='dazid'
                             rowClassName={(record, index) => getRowClassName(record, index)}
                             columns={listcolumns}
                             scroll={{x:'max-content'}}
                             dataSource={this.state.data}
                             pagination={paginationProps}
                             loading={this.state.loading}
                             onChange={this.handleTableChange}
                      />
                 </div>
        </Layout>
        {/* </Layout> */}
       </Layout>
  </ConfigProvider>
    );
  }
}

routes.register(
  "Contractseal.List",
  routeWithUserSession({
    path: "/contracts/seal",
    title: "提交的合同用印",
    render: pageProps => <SealList {...pageProps}/>,
  })
);
routes.register(
  "Contractseal.List1",
  routeWithUserSession({
    path: "/contracts/seal/approve",
    title: "待审批的合同用印",
    render: pageProps => <SealList {...pageProps}/>,
  })
);

// export default [
//   routeWithUserSession({
//     path: "/contracts/seal",
//     title: "我提交的合同用印",
//     render: pageProps => <SealList {...pageProps} />,
//   }),
//   routeWithUserSession({
//     path: "/contracts/seal/approve",
//     title: "待我审批的合同用印",
//     render: pageProps => <SealList {...pageProps} />,
//   }),
// ];
